package com.atguigu.juc.study.chapter14.rwlock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author : leimingchao
 * @date Date : 2022年06月22日 6:37
 */
public class MyResource {

    private Map<String, String> map = new HashMap<>();

    Lock lock = new ReentrantLock();

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();


    public void write(String key, String value) {

        lock.lock();

        try {

            System.out.println(Thread.currentThread().getName() + "\t" + "正在写入");

            map.put(key, value);

            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + "\t" + "完成写入");

        } finally {
            lock.unlock();
        }
    }

    public void writeByRw(String key, String value) {

        readWriteLock.writeLock().lock();

        try {

            System.out.println(Thread.currentThread().getName() + "\t" + "正在写入");

            map.put(key, value);

            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + "\t" + "完成写入");

        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public String read(String key) {
        lock.lock();

        try {

            System.out.println(Thread.currentThread().getName() + "\t" + "正在读取");
            String value = map.get(key);
            try {
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + "\t" + "完成读取" + "\t" + value);
            return value;
        } finally {
            lock.unlock();
        }
    }


    public String readByRw(String key) {
        readWriteLock.readLock().lock();

        try {

            System.out.println(Thread.currentThread().getName() + "\t" + "正在读取");
            String value = map.get(key);
            try {
                // TimeUnit.MILLISECONDS.sleep(200);
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + "\t" + "完成读取" + "\t" + value);
            return value;
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}
